package io.coderyeah.user.controller;

import io.coderyeah.basic.Result;
import io.coderyeah.basic.exception.BusinessException;
import io.coderyeah.user.dto.UserDTO;
import io.coderyeah.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;

@RestController
@RequestMapping("/user")
@Api("用户接口")
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation("用户邮箱注册")
    @PostMapping("/register/email")
    public Result registerByEmail(@RequestBody UserDTO userDTO) {
        try {
            return userService.register(userDTO);
        } catch (MessagingException e) {
            e.printStackTrace();
            return Result.fail("邮箱注册失败！请稍后再试");
        }
    }

    @ApiOperation("激活邮箱")
    @GetMapping("/active/{id}")
    public Result active(@PathVariable("id") String id) {
        return userService.active(id);
    }

    @ApiOperation("手机号注册")
    @PostMapping("/register/phone")
    public Result registerByPhone(@RequestBody UserDTO userDTO) {
        try {
            userService.registerByPhone(userDTO);
        } catch (BusinessException e) {
            return Result.fail("注册失败！" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("服务器繁忙,请稍后再试！" + e.getMessage());
        }
        return Result.success(null);
    }

    @ApiOperation("获取所有用户")
    @GetMapping
    public Result getAllUsers() {
        return Result.success(userService.list());
    }
}
